<template>
	<view class="container">

		<!-- Order Info Section -->
		<view class="card">
			<view class="card-title">订单信息</view>
			<view class="info-list">
				<view class="info-item">
					<text class="info-label">订单号</text>
					<text class="info-value">{{ order.order_id }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">创建时间</text>
					<text class="info-value">{{ order.created_at }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">支付方式</text>
					<text class="info-value">微信支付</text>
				</view>
				<view class="info-item">
					<text class="info-label">实付金额</text>
					<text class="info-value highlight">￥{{ order.fee }}</text>
				</view>
			</view>
		</view>

		<view class="card" v-if="order.status == 'paid'">
			<view class="card-title">临时密码</view>
			<view class="password-container">
				<view class="password-reminder">临时停车时记得核对密码</view>
				<view class="password-digits">
					<view class="password-digit" v-for="(digit, index) in password.split('')" :key="index">
						{{ digit }}
					</view>
				</view>
			</view>
		</view>


		<!-- Station Info Section -->
		<view class="card" v-if="order.status != 'paid'">
			<view class="card-title">站点信息</view>
			<view class="station-card">
				<view class="station-info">
					<view class="station-icon">
						<text class="cuIcon-location"></text>
					</view>
					<view class="station-content">
						<view class="station-title">{{ order.station.title }}</view>
						<view class="station-address">{{ order.station.address }}</view>
					</view>
				</view>
				<view class="station-actions">
					<view class="station-action" @click="openMap">
						<text class="action-icon cuIcon-location"></text>
						<text class="action-text">导航</text>
					</view>
					<view class="station-action" @click="callStation">
						<text class="action-icon cuIcon-phone"></text>
						<text class="action-text">电话</text>
					</view>
				</view>
			</view>
		</view>

		<view class="card" v-if="order.status != 'unpaid'">
			<view class="card-title">使用信息</view>
			<view class="usage-info">
				<view class="time-line">
					<view class="time-point start">
						<view class="point"></view>
						<view class="time-content">
							<view class="time-label">开始时间</view>
							<view class="time-value">{{ order.start_time }}</view>
						</view>
					</view>
					<view class="time-connector"></view>
					<view class="time-point end">
						<view class="point"></view>
						<view class="time-content">
							<view class="time-label">结束时间</view>
							<view class="time-value">{{order.end_time ? order.end_time : '进行中'}}</view>
						</view>
					</view>
				</view>
				<view class="duration-info">
					<view class="duration-label">使用时长</view>
					<view class="duration-value">{{runTime}}</view>
				</view>
			</view>
		</view>

		<!-- Fees Breakdown Section -->
		<view class="card">
			<view class="card-title">费用明细</view>
			<view class="fees-list">
				<view class="fee-item">
					<text class="fee-label">预付款</text>
					<text class="fee-value">￥{{ order.fee }}</text>
				</view>
				<view class="fee-item total">
					<text class="fee-label">实付金额</text>
					<text class="fee-value highlight">{{order.final_fee ? ("￥"+order.final_fee) : "订单未结束"}}</text>
				</view>
				<view class="fee-item total" v-if="order.status == 'refunding'">
					<text class="fee-label">该退回金额</text>
					<text class="fee-value highlight">￥{{ order.fee - order.final_fee }}</text>
				</view>
			</view>
		</view>

		<!-- Bottom Actions -->
		<view class="bottom-actions">
			<!-- <view class="action-btn primary" v-if="order.status == 'paid'" @click="finishOrder">
				结束租用
			</view> -->
			<view class="action-btn primary" v-if="order.status == 'completed'" @click="agianUse">
				再次租用
			</view>
		</view>


	</view>
</template>

<script>
	import {
		WX_CONFIG,
		API_CONFIG,
		STORAGE_KEYS
	} from '@/config/constants.js';

	export default {
		data() {
			return {
				orderId: '', // 订单ID参数
				showQrCodeModal: false, // 是否显示二维码弹窗
				order: {
					station: ""
				},
				end_time: "2025-05-01 12:08:00",
				runTime: "",
				password: "0000",
				statusPollingTimer: null,
				isPolling: false
			};
		},
		onShow() {
			if (!this.statusPollingTimer && this.orderId && this.order.status == 'paid') {
				this.startStatusPolling();
			}
		},
		onHide() {
			this.stopStatusPolling();
		},
		onUnload() {
			this.stopStatusPolling();
		},
		onLoad(options) {
			// 如果传入了订单ID，则获取对应订单详情
			if (options.id) {
				this.orderId = options.id;
				this.getOrderDetail(options.id);

				// 如果是"使用中"订单，启动轮询
				if (!this.statusPollingTimer && this.order.status == 'paid') {
					this.startStatusPolling();
				}
			}

			// 如果传入了订单状态，切换显示已完成订单的示例数据
			if (options.status && options.status === '2') {
				this.showCompletedOrderExample();
			}
		},
		methods: {
			// 开始轮询订单状态
			startStatusPolling() {
				// 确保没有正在运行的轮询
				this.stopStatusPolling();
				this.statusPollingTimer = setInterval(() => {
					if (!this.isPolling && this.orderId) {
						// 检查状态
						this.checkOrderStatus();
					}
				}, 2000);
			},
			// 停止轮询订单状态
			stopStatusPolling() {
				if (this.statusPollingTimer) {
					clearInterval(this.statusPollingTimer);
					this.statusPollingTimer = null;
				}
			},
			// 检测订单状态
			checkOrderStatus() {
				this.isPolling = true;
				uni.request({
					url: API_CONFIG.baseUrl + "/babyCar.Order/getOrderStatus?order_id="+String(this.orderId),
					method: "GET",
					success: (res) => {
						this.isPolling = false;
						// 检查接口返回数据是否有效
						if (res.data && res.data.data && this.order.status === 'paid') {
							const newStatus = res.data.data;
							console.log(newStatus,this.order.status);
							if (newStatus === 'returned' && this.order.status === 'paid') {
								this.finishOrder();
								this.getOrderDetail(this.orderId);
								this.stopStatusPolling();
							}
						}
					},
					fail: (err) => {
						this.isPolling = false;
						console.error('状态轮询失败:', err);
					}
				});
			},


			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 查看订单二维码
			viewQrCode() {
				this.showQrCodeModal = true;
			},

			// 关闭二维码弹窗
			closeModal() {
				this.showQrCodeModal = false;
			},


			// 再次租用功能
			rentAgain() {
				uni.switchTab({
					url: '/pages/index/index'
				});
			},

			// 打开地图导航
			openMap() {
				// 这里仅做演示，使用示例坐标
				uni.openLocation({
					latitude: 23.125178,
					longitude: 113.280637,
					name: this.order.stationTitle,
					address: this.order.stationAddress,
					scale: 18
				});
			},

			// 拨打站点电话
			callStation() {
				uni.makePhoneCall({
					phoneNumber: this.order.stationPhone,
					success: () => {
						console.log('拨打电话成功');
					},
					fail: () => {
						console.log('拨打电话失败');
					}
				});
			},

			// 获取当前时间字符串，格式：YYYY-MM-DD HH:MM:SS
			getCurrentTime() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},

			// 获取订单详情
			getOrderDetail(order_id) {
				uni.request({
					url: API_CONFIG.baseUrl + "/babyCar.Order/getOrderDetail?order_id=" + order_id,
					method: "GET",
					success: (res) => {
						// const prevStatus = this.order.status
						this.order = res.data.data
						this.password = uni.getStorageSync("password") || "0000"
						this.getRunTime(this.order.start_time, this.order.end_time)

						// 如果状态变为"已完成"，停止轮询
						if (this.order.status === 'completed') {
							this.stopStatusPolling();
						}

						// 如果状态变为"使用中"，启动轮询
						if (!this.statusPollingTimer && this.order.status === 'paid') {
							this.startStatusPolling();
						}
					},
					fail: (err) => {
						console.error(err);
					}
				})
			},

			// 获取时间差
			getRunTime(start_time, end_time) {
				if (!end_time) {
					this.runTime = "进行中"
					return
				}
				let time = new Date(end_time) - new Date(start_time);
				this.runTime = this.formatTimestamp(time);
			},

			// 格式化时间
			formatTimestamp(timestamp) {
				if (typeof timestamp !== 'number' || isNaN(timestamp)) {
					return '00:00:00'
				}
				// 绝对值转换时间戳
				const absoluteMs = Math.abs(timestamp)
				// 计算时分秒
				const totalSeconds = Math.floor(absoluteMs / 1000)
				const hours = Math.floor(totalSeconds / 3600)
				const minutes = Math.floor((totalSeconds % 3600) / 60)
				const seconds = totalSeconds % 60
				// 补零操作
				const pad = (n) => String(n).padStart(2, '0')
				return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`
			},

			// 再次使用
			agianUse() {
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: (res) => {
						let station_id = JSON.parse(res.result).station_id;
						let pile_idx = JSON.parse(res.result).pile_idx;
						uni.navigateTo({
							url: "/pages/rent/select?station_id=" + station_id + "&pile_idx=" +
								pile_idx
						})
					},
					fail: (err) => {
						console.error('扫码失败:', err);
						uni.showToast({
							title: '扫码已取消',
							icon: 'none'
						});
					}
				});
			},

			// 完成订单
			finishOrder() {
				const token = uni.getStorageSync("token");
				uni.request({
					url: API_CONFIG.baseUrl + "/babyCar.Order/update?token=" + token,
					method: "POST",
					data: this.order,
					success: (res) => {
						console.log(res);
						uni.clearStorageSync("password")
						this.getOrderDetail(this.orderId)
						uni.showToast({
							title: '订单已完成',
							icon: 'success',
							duration: 2000
						});
					},
					fail: (err) => {
						console.log(err);
					}
				})
			}
		},
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: #F8F8F8;
		padding-bottom: 80px;
		/* 为底部操作按钮腾出空间 */
	}

	.nav-bar {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		height: 44px;
		background-color: #FFD000;
		padding: 0 15px;
	}

	.nav-back {
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: flex-start;
		font-size: 24px;
	}

	.nav-title {
		font-size: 18px;
		font-weight: bold;
		color: #333333;
	}

	.nav-placeholder {
		width: 40px;
	}

	.status-card {
		background-color: #FF9500;
		padding: 20px;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.status-card.completed {
		background-color: #00AA00;
	}

	.status-header {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-bottom: 10px;
	}

	.status-icon {
		width: 40px;
		height: 40px;
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #FFFFFF;
		font-size: 20px;
		margin-right: 10px;
	}

	.status-text {
		font-size: 18px;
		color: #FFFFFF;
		font-weight: bold;
	}

	.status-time {
		font-size: 14px;
		color: #FFFFFF;
	}

	.card {
		background-color: #FFFFFF;
		border-radius: 10px;
		margin: 15px;
		overflow: hidden;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
	}

	.card-title {
		font-size: 16px;
		color: #333333;
		font-weight: bold;
		padding: 15px;
		border-bottom: 1px solid #F5F5F5;
	}

	.info-list {
		padding: 15px;
	}

	.info-item {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.info-item:last-child {
		margin-bottom: 0;
	}

	.info-label {
		font-size: 14px;
		color: #666666;
	}

	.info-value {
		font-size: 14px;
		color: #333333;
		text-align: right;
	}

	.info-value.highlight {
		color: #FF5000;
		font-weight: bold;
	}

	.station-card {
		padding: 15px;
	}

	.station-info {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-bottom: 15px;
	}

	.station-icon {
		width: 40px;
		height: 40px;
		background-color: #F5F5F5;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999999;
		font-size: 20px;
	}

	.station-content {
		flex: 1;
		margin-left: 10px;
	}

	.station-title {
		font-size: 16px;
		color: #333333;
		margin-bottom: 5px;
	}

	.station-address {
		font-size: 14px;
		color: #999999;
	}

	.station-actions {
		display: flex;
		flex-direction: row;
		border-top: 1px solid #F5F5F5;
		padding-top: 15px;
	}

	.station-action {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.action-icon {
		font-size: 24px;
		color: #666666;
		margin-bottom: 5px;
	}

	.action-text {
		font-size: 14px;
		color: #666666;
	}

	.usage-info {
		padding: 15px;
	}

	.time-line {
		display: flex;
		flex-direction: column;
		margin-bottom: 15px;
	}

	.time-point {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-bottom: 15px;
	}

	.time-point:last-child {
		margin-bottom: 0;
	}

	.point {
		width: 12px;
		height: 12px;
		border-radius: 50%;
		background-color: #FFD000;
		margin-right: 10px;
	}

	.time-point.start .point {
		background-color: #00AA00;
	}

	.time-point.end .point {
		background-color: #FF5000;
	}

	.time-connector {
		width: 2px;
		height: 30px;
		background-color: #DDDDDD;
		margin-left: 5px;
		margin-bottom: 15px;
	}

	.time-content {
		flex: 1;
	}

	.time-label {
		font-size: 14px;
		color: #666666;
		margin-bottom: 5px;
	}

	.time-value {
		font-size: 16px;
		color: #333333;
	}

	.duration-info {
		padding-top: 15px;
		border-top: 1px solid #F5F5F5;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}

	.duration-label {
		font-size: 14px;
		color: #666666;
	}

	.duration-value {
		font-size: 14px;
		color: #333333;
		font-weight: bold;
	}

	.fees-list {
		padding: 15px;
	}

	.fee-item {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		margin-bottom: 10px;
	}

	.fee-item:last-child {
		margin-bottom: 0;
	}

	.fee-item.total {
		margin-top: 15px;
		padding-top: 15px;
		border-top: 1px solid #F5F5F5;
	}

	.fee-label {
		font-size: 14px;
		color: #666666;
	}

	.fee-value {
		font-size: 14px;
		color: #333333;
	}

	.fee-value.highlight {
		color: #FF5000;
		font-size: 16px;
		font-weight: bold;
	}

	.fee-value.reduction {
		color: #00AA00;
	}

	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 70px;
		background-color: #FFFFFF;
		box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.05);
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: flex-end;
		padding: 0 15px;
		z-index: 10;
	}

	.action-btn {
		height: 40px;
		padding: 0 20px;
		margin-left: 10px;
		border-radius: 20px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
	}

	.action-btn.outline {
		border: 1px solid #DDDDDD;
		color: #666666;
	}

	.action-btn.primary {
		background-color: #FFD000;
		color: #333333;
	}

	.modal {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 999;
	}

	.modal-mask {
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.6);
	}

	.modal-content {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 80%;
		background-color: #FFFFFF;
		border-radius: 10px;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.modal-title {
		width: 100%;
		text-align: center;
		font-size: 18px;
		font-weight: bold;
		padding: 15px;
		border-bottom: 1px solid #F5F5F5;
	}

	.qrcode-container {
		padding: 20px;
	}

	.qrcode-image {
		width: 200px;
		height: 200px;
	}

	.qrcode-tips {
		font-size: 14px;
		color: #666666;
		margin-bottom: 20px;
	}

	.modal-close {
		width: 100%;
		height: 50px;
		line-height: 50px;
		text-align: center;
		font-size: 16px;
		color: #333333;
		border-top: 1px solid #F5F5F5;
	}

	.password-container {
		padding: 15px;
	}

	.password-reminder {
		font-size: 14px;
		color: #666666;
		margin-bottom: 10px;
	}

	.password-digits {
		display: flex;
		flex-direction: row;
		gap: 8px;
	}

	.password-digit {
		width: 48px;
		height: 56px;
		background-color: #FFD000;
		border-radius: 6px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28px;
		font-weight: bold;
		color: #333333;
	}
</style>